package web.base;

import com.alibaba.fastjson.JSONObject;
import web.utils.R;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Map;

@WebServlet("/*")
public class DisPatcherServlet extends HttpServlet {
    public static final String CONTROLLER_PACKAGE_NAME="web.controller";
/**/
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setCharacterEncoding("utf-8");
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        uri=uri.substring(contextPath.length()+1);
        ServletInputStream inputStream = req.getInputStream();
        StringBuffer params = new StringBuffer();
        byte[] bytes = new byte[1024 * 8];
        int len=0;
        while ((len=inputStream.read(bytes))!=-1){
            //对转换后的字符串进行URL解码；
            params.append(new String(bytes,0,len,"UTF-8"));
        }
        if (inputStream!=null){
            inputStream.close();
        }
        if (uri.indexOf("/")<0){
            resp.getWriter().print(R.error("请求需要用/分隔类名和方法名"));
        }
        String[] split = uri.split("/");
        String className=split[0];
        String methodName=split[1];
        try {
            Class<?> classz = Class.forName(CONTROLLER_PACKAGE_NAME + "." + className);
            Method method = null;
            try {
                method = classz.getMethod(methodName, JSONObject.class);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                method = classz.getMethod(methodName, HttpServletResponse.class);
            }
            //方法不是静态的必须使用对象才能调用
            Object object = classz.newInstance();
            Object invoke = method.invoke(object, JSONObject.parse(params.toString()));
            String responseText  = JSONObject.toJSONString(invoke);
            resp.getWriter().print(responseText);
        } catch (ClassNotFoundException e ) {
            e.printStackTrace();
            resp.getWriter().print(R.error("DispatcherServlet反射异常"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            resp.getWriter().print(R.error("参数异常请查看"));
        } catch (InstantiationException e) {
            e.printStackTrace();
            resp.getWriter().print(R.error("没有空参构造器"));
        } catch (InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
            resp.getWriter().print(R.error("方法运行时出现错误"));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setCharacterEncoding("utf-8");
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            System.out.println(stringEntry.getKey());
            String[] values = stringEntry.getValue();
            for (String value : values) {
                System.out.println(value);
            }
        }
        uri=uri.substring(contextPath.length()+1);
        if (!uri.contains("/")){
            resp.getWriter().print(R.error("请求需要用/分隔类名和方法名"));
        }
        String[] split = uri.split("/");
        String className=split[0];
        String methodName=split[1];
        try {
            Class<?> classz = Class.forName(CONTROLLER_PACKAGE_NAME + "." + className);
            Method method = null;
            boolean flag=true;
            try {
                method = classz.getMethod(methodName, Map.class);
            } catch (NoSuchMethodException e) {
//                e.printStackTrace();
                flag=false;
                method = classz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            }
            //方法不是静态的必须使用对象才能调用
            Object object = classz.newInstance();
//            Object result= method.invoke(object,parameterMap);
//            String responseText  = JSONObject.toJSONString(result);
//            resp.getWriter().print(responseText);
            if(flag) {
                Object result = method.invoke(object, parameterMap);
                //把返回值转成json字符串
                String responseText = JSONObject.toJSONString(result);
                resp.getWriter().print(responseText);
            }else{
                method.invoke(object,req,resp);
            }
        } catch (Exception e) {
            resp.getWriter().print(R.error("DispatcherServlet反射异常"));
        }
    }
}
